package com.hpin.mlxteacher.utils;


import android.app.ProgressDialog;
import android.content.Context;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.hpin.mlxteacher.base.MyApplication;

import java.util.HashMap;
import java.util.Map;

//import com.android.volley.Request;
//import com.android.volley.Response;
//import com.android.volley.VolleyError;
//import com.android.volley.toolbox.StringRequest;
//import com.hpin.mlxteacher.base.MyApplication;


/**
 * 网络请求工具
 * Created by Aaron on 2015/7/16.
 */
public class HttpUtil {

//    private ProgressDialog show;

//    private HttpUtil() {
//
//        httpUtils = new HttpUtils();
//        httpUtils.configCurrentHttpCacheExpiry(0);
//        httpUtils.configDefaultHttpCacheExpiry(0);
//        httpUtils.configSoTimeout(7 * 1000);
//        httpUtils.configTimeout(7 * 1000);
//    }
//
//    private static HttpUtil httpUtil = new HttpUtil();
//
//    public static HttpUtil getInstance() {
//
//        return httpUtil;
//    }

//    private HttpUtils httpUtils;

    /**
     * POST 请求
     *
     * @param message 提示信息
     * @param ctx     上下文对象
     * @param url     url地址
     * @param params  提交给服务器的json参数
     * @param tag     请求的tag (一般为当前请求页面的类的类名)
     * @param success 成功的监听
     * @param fail    失败的监听
     */
    public static void setPostRequest(String message, final Context ctx, String url, final String params, final String tag, final SuccessListener success, final FailListener fail) {

//        final ProgressDialog dialog = new ProgressDialog(ctx);

        final ProgressDialog show = ProgressDialog.show(ctx, message, Constant.WAIT);
//
////        dialog.setTitle(message);
////        dialog.setMessage(Constant.WAIT);
//
//        RequestParams param = new RequestParams();
//        param.addBodyParameter("data", params);
//
//        httpUtils.send(HttpRequest.HttpMethod.POST, url, param, new RequestCallBack<String>() {
//
//            @Override
//            public void onStart() {
//                super.onStart();
//
//
//                try {
//                    show.show();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//                LogUtil.e("TAG", "请求的json===>>>>" + params);
//
//            }
//
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//
//                try {
//                    if (show != null && show.isShowing()) {
//                        show.dismiss();
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//                LogUtil.e("TAG", "返回的json======>" + responseInfo.result);
//
//                if (success != null) {
//                    success.setOnSuccessListener(responseInfo.result);
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException e, String s) {
//                try {
//                    if (show != null && show.isShowing()) {
//                        show.dismiss();
//                    }
//                } catch (Exception ee) {
//                    ee.printStackTrace();
//                }
//
//                Toast.makeText(ctx, "请求数据失败!", Toast.LENGTH_SHORT).show();
//                LogUtil.e("TAG", "fail=====>" + s);
//
//                e.printStackTrace();
//
//                if (fail != null) {
//                    fail.setOnFailListener();
//                }
//            }
//        });

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                if (show != null && show.isShowing()) {
                    try {
                        show.dismiss();
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                LogUtil.e("TAG", "返回的json======>" + response);
                //成功回调
                if (success != null) {
                    success.setOnSuccessListener(response);
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

                LogUtil.e("tag", "==onErrorResponse==" + error.getMessage()
                    + "\r\n" + error.getLocalizedMessage() + "\r\n" +
                            error.toString() + "\r\n" +
                            error.getLocalizedMessage() + "\r\n" + error.hashCode());

                if (show != null && show.isShowing()) {
                    try {
                        show.dismiss();
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                Toast.makeText(ctx, "网络错误!", Toast.LENGTH_SHORT).show();

                if (fail != null) {
                    fail.setOnFailListener();
                }

            }

        }) {

            protected Map<String, String> getParams() {
                Map<String, String> param = new HashMap<String, String>();
                param.put("data", params);
                LogUtil.e("TAG", "请求的json===>>>>" + params);
                return param;
            }

        };

        //把请求加入队列
        ((MyApplication) ctx.getApplicationContext()).addToRequestQueue(stringRequest, tag);

    }



    /**
     * POST 请求
     *
     * @param ctx     上下文对象
     * @param url     url地址
     * @param params  提交给服务器的json参数
     * @param success 成功的监听
     * @param fail    失败的监听
     */
    public static void setPostNoWaring(final Context ctx, String url, final String params,
                                       String tag, final SuccessListener success, final FailListener fail) {

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                LogUtil.e("TAG", "返回的json===:" + response);

                //成功回调
                if (success != null) {
                    success.setOnSuccessListener(response);
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

                if (fail != null) {
                    fail.setOnFailListener();
                }

            }

        }) {

            protected Map<String, String> getParams() {
                Map<String, String> param = new HashMap<String, String>();
                param.put("data", params);

                LogUtil.e("TAG", "请求的json===>>>>" + params);

                return param;
            }

        };

        //把请求加入队列
        ((MyApplication) ctx.getApplicationContext()).addToRequestQueue(stringRequest, tag);

    }



    public interface SuccessListener {

        void setOnSuccessListener(String str);

    }


    public interface FailListener {

        void setOnFailListener();

    }

//    /**
//     * 上传图片
//     */
//    public String load(String url, byte[] bytes) {
//
//        String text = null;
//
//        try {
//            java.net.url url = new url(url);
//
//            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
//            uc.setRequestProperty(
//                    "Accept",
//                    "image/gif,   image/x-xbitmap,   image/jpeg,   image/pjpeg,   application/vnd.ms-excel,   " +
//                            "application/vnd.ms-powerpoint,   application/msword,   application/x-shockwave-flash,   application/x-quickviewplus,   */*");
//            uc.setRequestProperty("Accept-Language", "zh-cn");
//            uc.setRequestProperty("Content-type",
//                    "multipart/form-data;   boundary=---------------------------7d318fd100112");
//            uc.setRequestProperty("Accept-Encoding", "gzip,   deflate");
//            uc.setRequestProperty("User-Agent",
//                    "Mozilla/4.0   (compatible;   MSIE   6.0;   Windows   NT   5.1)");
//            uc.setRequestProperty("Connection", "Keep-Alive");
//            uc.setDoOutput(true);
//            uc.setRequestMethod("POST");
//            //设置容许输出
//            uc.setDoOutput(true);
//            //不使用缓存
//            uc.setUseCaches(false);
//            //超时时间10秒
//            uc.setConnectTimeout(10000);
//
//            OutputStream out = uc.getOutputStream();
//            out.write(bytes);
//            out.flush();
//            out.close();
//
//            int code = uc.getResponseCode();
//            String sCurrentLine = "";
//            String sTotalString = "";
//            if (code == 200) {
//                java.io.InputStream is1 = uc.getInputStream();
//                BufferedReader reader = new BufferedReader(
//                        new InputStreamReader(is1));
//                while ((sCurrentLine = reader.readLine()) != null)
//                    if (sCurrentLine.length() > 0)
//                        sTotalString = sTotalString + sCurrentLine.trim();
//            }
//            text = sTotalString;
//            LogUtil.e("net", text);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return text;
//
//    }

}
